package com.hopedove.tempdemo.utils

import android.graphics.Color
import android.widget.GridLayout
import android.widget.TextView
import com.google.gson.JsonElement

/**
 *  ds 表格转换帮助
 */

data class GridLayoutCell(
    val value: String = "",
    val span: Int = 1,
    val dimensionSize: Pair<Int, Int> = Pair(0, 0),
)

fun jsonElementParseTo(jsonElement: JsonElement): List<GridLayoutCell> {
    if (jsonElement.isJsonObject &&
        jsonElement.asJsonObject.has("head") &&
        jsonElement.asJsonObject.has("data")
    ) {
        val head = jsonElement.asJsonObject.getAsJsonArray("head")
        val data = jsonElement.asJsonObject.getAsJsonArray("data")
        val rows = data.size() + 1
        val cols = head.sumBy { it.asJsonArray[1].asInt }
        val size = Pair(rows, cols)

        val list = mutableListOf<Pair<String, Int>>()
        head.forEach {
            val item = it.asJsonArray.let {
                Pair(it[0].asString, it[1].asString.toInt())
            }
            list.add(item)
        }


        data.forEach { arr ->
            arr.asJsonArray.forEach {
                val item = Pair(it.asString, 1)
                list.add(item)
            }
        }


        return list.map { r ->
            GridLayoutCell(r.first, r.second, dimensionSize = size)
        }
    }
    return emptyList()
}


fun fillGridLayout(
    layout: GridLayout,
    rows: Int,
    columns: Int,
    cells: List<GridLayoutCell>
): GridLayout {
    layout.apply {
        rowCount = rows
        columnCount = columns
        setPadding(1, 1, 1, 1)
    }

    cells.forEach { cell ->
        val widthSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL)
        val heightSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL)
        val layoutParam = GridLayout.LayoutParams(widthSpec, heightSpec)
        layoutParam.setMargins(1, 1, 1, 1)
        val view = TextView(layout.context).apply { text = cell.value }
        view.setBackgroundColor(Color.WHITE)
        layout.addView(view, layoutParam)
    }

    return layout
}